<template>
  <div class="blacklist-wrap">
    <div class="tip config--new">
      <span v-if="flag !== 'ecommerce'">{{$t('config.channel.webchatGlobalMessage')}}</span>
      <span>{{$t('configLazyLoad.blackList.tips')}}</span>
      <!--<span v-show="activeName === 'customerIntention'">{{$t('config.channel.intentionMessage')}}</span>-->
    </div>
    <affix :label="$t('configLazyLoad.blackList.searchConditions')"></affix>
    <el-form :model="ruleForm" ref="ruleForm" label-width="130px" label-position="top" class="clearfix form-wrap">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item :label="$t('configLazyLoad.blackList.customerId')">
            <el-input size="mini" class="el-input-title" v-model.trim="ruleForm._id"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('configLazyLoad.blackList.customerName')">
            <el-input size="mini" class="el-input-title" v-model.trim="ruleForm.sName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('configLazyLoad.blackList.lockTime')" class="padd-r-10">
            <el-col :span="11" style="padding-left: 0px;padding-right: 0px">
              <el-date-picker
                      v-model="ruleForm.lastAddBlackTime_start"
                      type="datetime"
                      :id="'lastAddBlackTime_start'"
                      :placeholder="$t('configLazyLoad.public.beginTime')"
                      :editable="false"
                      style="width: 100%">
              </el-date-picker>
            </el-col>
            <el-col class="bet" :span="2" style="padding-left: 6px">
            </el-col>
            <el-col :span="11" style="padding-right: 0px">
              <el-date-picker
                      v-model="ruleForm.lastAddBlackTime_end"
                      type="datetime"
                      :id="'lastAddBlackTime_end'"
                      :placeholder="$t('configLazyLoad.public.endTime')"
                      :editable="false"
                      style="width: 100%">
              </el-date-picker>
            </el-col>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item :label="$t('configLazyLoad.blackList.confirmLock')">
            <el-select size="mini" v-model="ruleForm.isUntieFromBlack" :placeholder="$t('public.pleasePick')" style="width:100%">
              <el-option  :label="$t('configLazyLoad.public.all')" :value="''"></el-option>
              <el-option
                      v-for="item in peerOptions"
                      :key="item.value"
                      :label="item.name"
                      :value="item.value"
                      >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('configLazyLoad.blackList.applyUnlock')">
            <el-select size="mini" v-model="ruleForm.applyUntieBlack" :placeholder="$t('public.pleasePick')" style="width:100%">
              <el-option  :label="$t('configLazyLoad.public.all')" :value="''"></el-option>
              <el-option
                      v-for="item in peerOptions"
                      :key="item.value"
                      :label="item.name"
                      :value="item.value"
                      >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="flag === 'kf'">
          <el-form-item :label="$t('configLazyLoad.blackList.blackListType')">
            <el-select size="mini" v-model="ruleForm.type" :placeholder="$t('public.pleasePick')" style="width:100%">
              <el-option
                      v-for="item in blackTypeOptions"
                      :key="item.value"
                      :label="item.name"
                      :value="item.value"
                      >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="submit">
        <el-button class="primary_btn" @click.stop="reset">{{$t('public.reset')}}</el-button>
        <el-button type="primary" class="primary_btn" @click.stop="reshList">{{$t('public.search2')}}</el-button>
      </div>
    </el-form>
    <affix :label="$t('configLazyLoad.public.searchResult')"></affix>
    <div class="tool">
      <div class="add-wapper" style="float: left">
        <span @click.stop="reshList" class="creat-text"><i class="iconfont icon-shuaxin"></i><span>{{$t('public.refresh')}}</span></span>
        <span @click.stop="editBlackReasonDialog({}, 'batch')" class="creat-text" :class="isDisabled?'icon-disabled':''"><i class="iconfont icon-beizhu"></i><span>{{$t('configLazyLoad.blackList.batchEditLockReason')}}</span></span>
        <span @click.stop="untieBlackUserDialog({}, 'batch')"  class="creat-text" :class="isDisabled?'icon-disabled':''"><i class="iconfont icon-jiesuo"></i><span>{{$t('configLazyLoad.blackList.batchUnLock')}}</span></span>
        <span @click.stop="delBlackListWarn({}, 'batch')" class="creat-text" :class="isDisabled?'icon-disabled':''"><i class="iconfont icon-shanchu"></i><span>{{$t('webchat.moreDel')}}</span></span>
      </div>
      <div class="pag-wapper" style="float: right">
        <pagination
                :small="true"
                :currentPage="currPage"
                :count="count"
                @turnPage="trunPages"
                :totalPage="Math.ceil(count/10)"
                >
        </pagination>
      </div>
    </div>
    <el-table :data="tableData" style="width: 100%" :highlight-current-row="true" :stripe="true" ref="multipleTable" @selection-change="handleSelectionChange" size="mini">
      <el-table-column
              type="selection"
              width="50">
      </el-table-column>
      <template v-for="item in tableHeader">
        <el-table-column
                v-if="item.prop !== ''"
                :prop="item.prop"
                :label="item.label">
        </el-table-column>
        <el-table-column
                v-if="item.prop === ''"
                :label="item.label">
          <template scope="scope">
            <el-button @click="editBlackReasonDialog(scope.row, 'single')" type="text" size="small" class="updata" style="white-space: break-spaces; word-break: break-word; text-align:left; margin-left: 10px;">{{$t('configLazyLoad.blackList.editLockReason')}}</el-button>
            <el-button @click="untieBlackUserDialog(scope.row, 'single')" type="text" size="small" class="updata" v-show="scope.row.isUntieFromBlack !== 1">{{$t('configLazyLoad.blackList.unlock')}}</el-button>
            <el-button type="text" @click="delBlackListWarn(scope.row, 'single')" size="small" class="del">{{$t('public.delete')}}</el-button>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="batchOrSingleFlag === 'single' ? $t('config.channel.checkBlackName', {name: custName}) : $t('configLazyLoad.blackList.batchEditLockReason')" :visible.sync="showEditDialog" width="30%">
      <span>{{$t('configLazyLoad.blackList.lockReason')}}:</span>
      <el-input size="mini" type="textarea" v-model="blackReason" :rows="4"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click.stop="showEditDialog = false">{{$t('public.cancel')}}</el-button>
        <el-button type="primary" class="primary_btn" @click.stop="checkBlackReason">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="batchOrSingleFlag === 'single'?$t('configLazyLoad.blackList.unlock'):$t('configLazyLoad.blackList.batchUnLock')" :visible.sync="showUntieDialog" width="30%">
      <span v-text="batchOrSingleFlag === 'single'?$t('config.channel.untieBlackUser', {name: custName}):$t('configLazyLoad.blackList.confirmBatchEditLock')">{{}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click.stop="showUntieDialog = false">{{$t('public.cancel')}}</el-button>
        <el-button type="primary" class="primary_btn" @click.stop="untieBlackUser">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import affix from '@/components/ui-modules/affix/Affix.vue'
  import Pagination from '@/components/public-modules/card/Pagination'
  import {deepClone, getCache, getFormatDateTime, resetForm} from '@/utils/m7Utils'
  export default {
    name: 'blackListChat',
    data () {
      return {
        //        搜索条件
        ruleForm: {
          _id: '',
          sName: '',
          lastAddBlackTime_start: '',
          lastAddBlackTime_end: '',
          isUntieFromBlack: '',
          applyUntieBlack: '',
          type: ''
        },
        flag: this.$store.getters.isEcommerce ? 'ecommerce' : 'kf',
        tableHeader: [
          {prop: '_id', label: this.$t('configLazyLoad.blackList.customerId')},
          {prop: 'sName', label: this.$t('configLazyLoad.blackList.customerName')},
          {prop: 'ip', label: this.$t('configLazyLoad.blackList.customerIp')},
          {prop: 'type', label: this.$t('configLazyLoad.blackList.blackListType')},
          {prop: 'displayName', label: this.$t('configLazyLoad.blackList.lockAgent')},
          {prop: 'lastAddBlackTime', label: this.$t('configLazyLoad.blackList.lockTime')},
          {prop: 'addBlackReason', label: this.$t('configLazyLoad.blackList.lockReason')},
          {prop: 'isUntieFromBlackName', label: this.$t('configLazyLoad.blackList.confirmLock')},
          {prop: 'addBlackCount', label: this.$t('configLazyLoad.blackList.lockTimes')},
          {prop: 'lastUntieBlackTime', label: this.$t('configLazyLoad.blackList.lastlockTime')},
          {prop: 'applyUntieBlackName', label: this.$t('configLazyLoad.blackList.applyUnlock')},
          {prop: '', label: this.$t('public.operate')}
        ],
        peerOptions: [{name: this.$t('public.yes'), value: '1'}, {name: this.$t('public.no'), value: '0'}],
        blackTypeOptions: [{name: this.$t('configLazyLoad.blackList.visitorsBlackList'), value: ''}, {name: this.$t('configLazyLoad.blackList.ipBlackList'), value: 'ip'}],
        tableData: [],
        pages: 1,
        count: 0,
        currPage: 1,
        showEditDialog: false, // 编辑封禁原因弹窗标志
        blackReason: '', // 封禁原因
        custName: '', // 访客名称
        batchOrSingleFlag: 'single', // 单个操作还是批量操作的标志
        currentId: '', // 当前id
        currentIp: '',
        showUntieDialog: false, // 解封弹窗标志
        multipleSelection: [],
        multipleSelectionIp: [],
        isDisabled: true // 批量操作的icon能否可点击
      }
    },
    methods: {
      trunPages (val) { // 翻页
        this.currPage = val
        this.getBlackList()
      },
      reset () {
        this.ruleForm._id = ''
        this.ruleForm.sName = ''
        this.ruleForm.lastAddBlackTime_start = ''
        this.ruleForm.lastAddBlackTime_end = ''
        this.ruleForm.isUntieFromBlack = ''
        this.ruleForm.applyUntieBlack = ''
        this.ruleForm.type = ''
      },
      reshList () { // 刷新 or 点击查询
        this.currPage = 1
        this.getBlackList()
      },
      handleSelectionChange (val) {
        let idArr = []
        let ipArr = []
        if (val.length > 0) {
          this.isDisabled = false
          val.forEach(item => {
            idArr.push(item._id)
            ipArr.push(item.ip)
          })
        } else {
          this.isDisabled = true
        }
        this.multipleSelection = idArr
        this.multipleSelectionIp = ipArr
      },
      editBlackReasonDialog (obj, flag) { // 打开编辑封禁原因的窗口
        this.custName = obj.sName || ''
        this.blackReason = obj.addBlackReason || ''
        this.batchOrSingleFlag = flag
        if (flag === 'single') {
          this.currentId = obj._id
          this.currentIp = obj.ip
        } else if (flag === 'batch') {
          if (this.isDisabled) { // 没有选择一个选项，禁止点击
            return
          }
        }
        this.showEditDialog = true
      },
      untieBlackUserDialog (obj, flag) { // 打开解封窗口
        this.custName = obj.sName || ''
        this.batchOrSingleFlag = flag
        if (flag === 'single') {
          this.currentId = obj._id
          this.currentIp = obj.ip
        } else if (flag === 'batch') {
          if (this.isDisabled) { // 没有选择一个选项，禁止点击
            return
          }
        }
        this.showUntieDialog = true
      },
      untieBlackUser () { // 解封/批量解封
        this.showUntieDialog = false
        let data = {}
        let idArr = []
        let ipArr = []
        if (this.batchOrSingleFlag === 'single') {
          idArr.push(this.currentId)
          data._id = idArr
          if (this.ruleForm.type === 'ip') {
            ipArr.push(this.currentIp)
            data.ip = ipArr
            data.type = this.ruleForm.type
          }
        } else {
          if (this.ruleForm.type === 'ip') {
            data.ip = this.multipleSelectionIp || []
            data.type = this.ruleForm.type
          } else {
            data._id = this.multipleSelection || []
          }
        }
        this.$store.dispatch('untieBlackUser', data).then((resp) => {
          if (resp && resp.success) {
            if (this.batchOrSingleFlag === 'single') {
              this.$message.success(this.$t('configLazyLoad.blackList.unlockSuccess'))
            } else {
              this.$message.success(this.$t('configLazyLoad.blackList.batchUnlockSuccess'))
            }
            this.getBlackList()
          } else {
            if (this.batchOrSingleFlag === 'single') {
              this.$message.error(this.$t('configLazyLoad.blackList.unlockFaile'))
            } else {
              this.$message.error(this.$t('configLazyLoad.blackList.batchFaile'))
            }
          }
        })
      },
      checkBlackReason () { // 修改/批量修改封禁原因
        if (!this.blackReason) {
          this.$message.error(this.$t('configLazyLoad.blackList.lockResultMust'))
          return
        }
        this.showEditDialog = false
        let data = {}
        let idArr = []
        let ipArr = []
        if (this.batchOrSingleFlag === 'single') {
          idArr.push(this.currentId)
          data._id = idArr
          if (this.ruleForm.type === 'ip') {
            ipArr.push(this.currentIp)
            data.ip = ipArr
            data.type = this.ruleForm.type
          }
        } else {
          if (this.ruleForm.type === 'ip') {
            data.ip = this.multipleSelectionIp || []
            data.type = this.ruleForm.type
          } else {
            data._id = this.multipleSelection || []
          }
        }
        data.addBlackReason = this.blackReason
        this.$store.dispatch('editBlackReason', data).then((resp) => {
          if (resp && resp.success) {
            this.$message.success(this.$t('configLazyLoad.public.editSuccess'))
            this.getBlackList()
          } else {
            this.$message.error(this.$t('configLazyLoad.public.editError'))
          }
        })
      },
      getBlackList (currPage) {
        let form = deepClone(this.ruleForm)
        if (form.lastAddBlackTime_start) {
          form.lastAddBlackTime_start = getFormatDateTime(form.lastAddBlackTime_start)
        }
        if (form.lastAddBlackTime_end) {
          form.lastAddBlackTime_end = getFormatDateTime(form.lastAddBlackTime_end)
        }
        if (form.lastAddBlackTime_end && form.lastAddBlackTime_start) {
          if (form.lastAddBlackTime_end < form.lastAddBlackTime_start) {
            this.$message.error(this.$t('configLazyLoad.blackList.endTimeCannotEary'))
            return
          }
        }
        if (form.applyUntieBlack) {
          form.applyUntieBlack = parseInt(form.applyUntieBlack)
        }
        if (form.isUntieFromBlack) {
          form.isUntieFromBlack = parseInt(form.isUntieFromBlack)
        }
        form.page = currPage || this.currPage || 1
        form.limit = 10
        this.$store.dispatch('queryBlackUser', form).then((resp) => {
          if (resp && resp.success) {
            console.log(resp.list)
            let list = resp.list
            if (list.length > 0) {
              for (var i = 0; i < list.length; i++) {
                let operatorData = getCache('agents', list[i].addBlackAgent)
                list[i].displayName = ''
                if (operatorData) {
                  list[i].displayName = operatorData.displayName
                }
                if (!list[i].type) {
                  list[i].type = this.$t('configLazyLoad.blackList.visitorsBlackList')
                }
                if (list[i].applyUntieBlack === 1) { // 访客申请解封
                  list[i].applyUntieBlackName = this.$t('public.yes') + ' (' + list[i].applyUntieBlackTime + ')'
                } else if (list[i].applyUntieBlack === 0) {
                  list[i].applyUntieBlackName = this.$t('public.no')
                }
                if (list[i].isUntieFromBlack === 1) {
                  list[i].isUntieFromBlackName = this.$t('public.yes')
                } else if (list[i].isUntieFromBlack === 0) {
                  list[i].isUntieFromBlackName = this.$t('public.no')
                }
              }
            }
            this.tableData = list
            this.count = resp.count
          }
        })
      },
      delBlackList (obj, flag) {
        let data = {}
        if (flag === 'single') {
          data._id = [obj._id]
          if (this.ruleForm.type === 'ip') {
            data.ip = [obj.ip]
            data.type = this.ruleForm.type
          }
        } else {
          if (this.ruleForm.type === 'ip') {
            data.ip = this.multipleSelectionIp || []
            data.type = this.ruleForm.type
          } else {
            data._id = this.multipleSelection || []
          }
        }
        this.$store.dispatch('deleteBlackUser', data).then((resp) => {
          if (resp && resp.success) {
            this.$message.success(this.$t('configLazyLoad.public.deleteSuccess'))
            this.getBlackList(1)
          } else {
            this.$message.error(this.$t('configLazyLoad.public.deleteFailure'))
          }
        })
      },
      delBlackListWarn (obj, flag) {
        let str = ''
        if (flag === 'single') {
          let custName = obj.sName || ''
          str = this.$t('configLazyLoad.blackList.deletCustNameFromBlackList', {custName: custName})
        } else {
          str = this.$t('configLazyLoad.blackList.confirmBatchUnlockAndDelete')
        }
        this.$confirm(str, this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          this.delBlackList(obj, flag)
        }).catch(() => {
          console.log(this.$t('public.cancel'))
        })
      }
    },
    beforeMount () {
      this.getBlackList()
    },
    components: {
      affix,
      Pagination
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .blacklist-wrap
    padding 20px
    .tip
      font-size: 12px;
      padding: 10px;
      color: #878787;
      background-color: #f4f5f9;
      margin-bottom 20px
    .ui-affix
      padding-bottom 0
    .form-wrap
      margin-bottom 40px
    .submit
      float right
    .padd-r-10
      padding-right 10px
    .bet
      &:before
        content: ''
        display inline-block
        width 15px
        height 1px
        margin 3px 12px
        background $cf-gray5
        text-align center
    .wapper
      display flex
      flex-direction column
    .tool
      border 1px solid #e7e7eb
      border-bottom 0
      padding  8px 0px
      height 30px
      justify-content space-between
    .add-wapper
      line-height 30px
      cursor pointer
      span
        margin-left 5px
    .creat-text
      cursor pointer
      .iconfont
        color $c-main
    .del
      color $c-pink
    .icon-disabled
      cursor not-allowed
      .iconfont
        color #9D9B9D
</style>
